var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
// var logger = require('morgan');
const session = require("express-session")
const md5 = require('md5');


// 创建express实例
var app = express();

// 使用环境变量
require("dotenv").config();
// 让express捕获异步错误
require("express-async-errors");

// 引入数据库
require("./dao/db");

// 使用各种中间件
// app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use("/", express.static(path.join(__dirname, 'public')));
app.use(session({   // 验证码验证需要用到session
    secret: md5(process.env.SESSION_SECURE),
    resave: true,
    saveUninitialized: true,
}))

// token中间件
app.use(require("./routes/middlewares/verdationToken"));

// 使用路由
app.use("/api/admin", require("./routes/adminRouter"));
app.use("/res/captcha", require("./routes/captchaRouter"));
app.use("/api/banner", require("./routes/bannerRouter"));
app.use("/api/upload", require("./routes/uploadRouter"));
app.use("/api/blogtype", require("./routes/blogTypeRouter"));
app.use("/api/blog", require("./routes/blogRouter"));
app.use("/api/project", require("./routes/projectRouter"));
app.use("/api/setting", require("./routes/settingRouter"));
app.use("/api/about", require("./routes/aboutRouter"));
app.use("/api/message", require("./routes/messageRouter"));
app.use("/api/comment", require("./routes/commentRouter"));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// 错误处理中间件
app.use(require("./routes/middlewares/errorHanler"));

module.exports = app;